package com.model;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;

import textanalyzer.MainAnalyzer;

public class TagBasedDataModel extends DataModel {

	public TagBasedDataModel(String datasource, String url, String username,
			String password, String driverName) {
		this.datasource = datasource;
		this.url = url;
		this.username = username;
		this.password = password;
		this.driverName = driverName;
	}

	public HashMap<String, Integer> getTagVectorbyImage(Long imageID) {
		HashMap<String, Integer> tagVector = new HashMap<String, Integer>();

		ResultSet rSet = null;

		try {
			String sqlString = "SELECT Tags from searchhistory where ImageID = '"
					+ imageID + "'";
			rSet = fetch(sqlString);
			while (rSet.next()) {
				String currTags = rSet.getString("Tags");
				String[] tags = currTags.split(",");

				for (int i = 0; i < tags.length; i++) {
					String tmpTag = tags[i];
					if (!tagVector.containsKey(tmpTag))
						tagVector.put(tmpTag, 1);
					else
						tagVector.put(tmpTag, tagVector.get(tmpTag) + 1);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return tagVector;
	}

	public ResultSet getTuplesFilteredByKeyword(String keyword)
			throws Exception {
		ResultSet rs;

		String sqlString = "select RequestID, Tags, ImageID from searchhistory where Keyword='"
				+ keyword + "' order by ImageID";

		try {
			System.out.println(sqlString);
			rs = fetch(sqlString);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}

		return rs;

	}

	@Override
	public int saveUserFeedback(HashMap contextMap, long userID,
			String keyword, String url, long imageId) throws Exception {

		String returnedTags = contextMap.get("tags").toString();

		// /System.out.println("user feed back"+userID);

		Map<String, Integer> tagVector = new LinkedHashMap<String, Integer>();
		MainAnalyzer nAnalyzer = new MainAnalyzer();
		tagVector = nAnalyzer.identifyContext(returnedTags);
		String tags = "";
		Set tagVectorSet = tagVector.entrySet();
		Iterator i = tagVectorSet.iterator();
		Map.Entry<String, Integer> me = (Map.Entry<String, Integer>) i.next();
		tags = tags + me.getKey().toString();
		int j = 0;
		while (i.hasNext()) {
			if (j == 4)
				break;
			j++;
			me = (Map.Entry<String, Integer>) i.next();
			tags = tags + "," + me.getKey().toString();
		}

		// /////String tags = returnedTags.replaceAll("#", ",");

		try {
			saveUserFeedback(tags, userID, keyword, url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}

		return 0;
	}

	public int saveUserFeedback(String tags, long userID, String keyword,
			String url) throws Exception {
		long imageID = getImgID(url);
		long newImageID = 0;
		if (imageID == 0) {
			newImageID = getImageCount() + 1;
		} else {
			newImageID = imageID;
		}

		long reqID = getReqCount() + 1;

		String sql_saveToHistory = "Insert into searchhistory (requestID, imageID, tags, keyword) values('"
				+ reqID
				+ "','"
				+ newImageID
				+ "','"
				+ tags
				+ "','"
				+ keyword
				+ "')";

		if (imageID == 0) {
			try {
				System.out.println("sql_dfdfddf");
				String sql_saveToImage = "Insert into Image (ImageID,ImageURL) values('"
						+ newImageID + "','" + url + "')";
				// sql_saveToHistory="Insert into searchhistory (requestID, imageID, tags, userID, keyword) values('"+reqID+"','"+newImageID+"','"+tags+"','"+userID+"','"+keyword+"')";
				save(sql_saveToImage);
				save(sql_saveToHistory);
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}

		} else {
			try {
				save(sql_saveToHistory);
			} catch (ServletException e) {

				e.printStackTrace();
				throw e;
			}
		}

		return 1;
	}

	protected void save(String sql) throws ServletException {
		System.out.println(sql);
		try {
			if (c == null) {
				connect();
			}
			c.createStatement().executeUpdate(sql);
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}

	private long getReqCount() throws Exception {
		ResultSet rSet = null;
		long count = 0;
		String sql = "select MAX(RequestID) from searchhistory";
		try {
			rSet = fetch(sql);
			if (rSet != null) {
				while (rSet.next()) {
					count = rSet.getInt("MAX(RequestID)");
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

		return count;
	}

	private long getImageCount() throws Exception {
		ResultSet rSet = null;
		long count = 0;
		String sql = "select MAX(ImageID) from Image";
		try {
			rSet = fetch(sql);
			if (rSet != null) {
				while (rSet.next()) {
					count = rSet.getInt("MAX(ImageID)");
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

		return count;
	}

	private long getImgID(String URL) throws Exception {
		long imageID = 0;
		ResultSet rSet = null;
		String sql = "select ImageID from Image where ImageURL='" + URL + "'";
		try {
			rSet = fetch(sql);
			if (rSet != null) {
				while (rSet.next()) {
					imageID = rSet.getInt("ImageID");
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return imageID;
	}

}
